package me.czmc.websocketdemo;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.orhanobut.logger.Logger;

import org.java_websocket.WebSocket;

import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;
import ua.naiksoftware.stomp.LifecycleEvent;
import ua.naiksoftware.stomp.Stomp;
import ua.naiksoftware.stomp.StompHeader;
import ua.naiksoftware.stomp.client.StompClient;
import ua.naiksoftware.stomp.client.StompMessage;

public class MainActivity extends AppCompatActivity {
    @BindView(R.id.et_url)
    EditText et_url;
    @BindView(R.id.et_url1)
    EditText et_url1;
    @BindView(R.id.et_msg)
    EditText et_msg;
    @BindView(R.id.tv_text)
    TextView tv_text;
    private StompClient mStompClient;
    private int offset;

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @OnClick({R.id.btn_connection, R.id.btn_send})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.btn_connection:
                start(et_url.getText().toString(),et_url1.getText().toString());
                break;
            case R.id.btn_send:
                if (mStompClient != null) {
                    Message message = new Message("test","test");
                    Gson gson = new Gson();
                    String str = gson.toJson(message);
                    mStompClient.send("/app/room/1008/chat", str).subscribe();
                    et_msg.setText("");
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Logger.init("WebSocketDmo");
        ButterKnife.bind(this);

    }
    public void append(String s){
       s= s.trim()+"\n";
        tv_text.append(s);
    }

    private void start(String s,String sub) {
        mStompClient = Stomp.over(WebSocket.class, s);
        mStompClient.connect(Arrays.asList(new StompHeader[]{new StompHeader("userId","clent")}));
        mStompClient.topic("/app/"+sub).subscribe(new Action1<StompMessage>() {
            @Override
            public void call(final StompMessage stompMessage) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Message msg=null;
                        TypeAdapter<Message> adapter = new Gson().getAdapter(Message.class);
                        if ((msg = new Gson().fromJson(stompMessage.getPayload(),Message.class))!=null)
                            append(msg.getUsername());
                        else {
                            append(stompMessage.getPayload());
                        }
                    }
                });
                Logger.i(stompMessage.getPayload());
            }
        });
        mStompClient.lifecycle().subscribe(new Action1<LifecycleEvent>() {
                                               @Override
                                               public void call(LifecycleEvent lifecycleEvent) {
                                                   switch (lifecycleEvent.getType()) {

                                                       case OPENED:
                                                           runOnUiThread(new Runnable() {
                                                               @Override
                                                               public void run() {
                                                                   append("connection!");
                                                               }
                                                           });
                                                           Logger.i("Stomp connection opened");
                                                           break;

                                                       case ERROR:
                                                           runOnUiThread(new Runnable() {
                                                               @Override
                                                               public void run() {
                                                                   append("error!");
                                                               }
                                                           });

                                                           Logger.i("Error", lifecycleEvent.getException());
                                                           break;

                                                       case CLOSED:
                                                           runOnUiThread(new Runnable() {
                                                               @Override
                                                               public void run() {
                                                                   tv_text.append("closed!");
                                                               }
                                                           });
                                                           Logger.i("Stomp connection closed");
                                                           break;
                                                   }
                                               }
                                           }

        );
    }
}
